/* eslint-disable array-callback-return */
import { routerRedux } from 'dva/router';
import { message } from 'antd';
import { getProductAttr, getAreaPrice, submit } from '@/services/quotation';

export default {
  state: {
    preQuoInfo: {}, // 前一步报价单
    productList: [], // 所有产品数据列表
    packIndex: 0, // 包id
    packList: [
      // 产品列表
      {
        listQuoPd: [
          {
            pdId: '', // 产品id
            pdName: '', // 产品名称
            summary: '', // 产品概述
            pdCate: '', //  产品类型
            listAttr: [
              {
                attrId: '', // 属性id
                attrName: '', // 属性名称
                dictType: '', // 属性字典
                attrValList: '', // 属性值集合
              },
            ], //  	产品属性集合
          },
        ],
        priceList: [
          // 产品地区定价集合
          {
            id: 1,
            areaId: '', // 地区id 全国为1
            quotePrice: 0, // 报价金额
            suggPrice: 0, // 建议售价
            taxMoney: 0, // 税金
          },
        ],
      },
    ], // 页签包数据
    isGoBack: false,
  },
  effects: {
    // 获取产品属性列表
    *fetchProductAttr(
      {
        payload: { preQuoInfo },
      },
      { call, put }
    ) {
      const response = yield call(getProductAttr, { pdIds: preQuoInfo.pdId });
      yield put({
        type: 'updateModelData',
        payload: {
          productList: [],
          preQuoInfo,
          packList: [{ listQuoPd: preQuoInfo.listQuoPd, priceList: [] }],
        },
      });
      if (response.success) {
        const { packList } = preQuoInfo;
        packList.map(pack => {
          const temp = pack;
          if (pack.listQuoPd.length) {
            temp.areaPriceId = 1; // 价格地区id
            temp.priceList = [
              //  产品地区定价集合 默认一组
              {
                id: 1,
                areaIdList: [], // 地区id集合 【】
                areaId: '', // 地区id字符串 全国为1
                quotePrice: 0, // 报价金额
                suggPrice: 0, // 建议售价
                taxMoney: 0, // 税金
              },
            ];
            pack.listQuoPd.map(pd => {
              const tempValues = pd;
              tempValues.listAttr = []; // 产品选择的属性
              response.data.map(item => {
                if (pd.pdId === item.pdId) {
                  tempValues.pdName = item.pdName;
                  tempValues.summary = item.summContent || '--';
                  tempValues.pdCate = item.pdCate;
                  tempValues.pdAttrVOs = item.pdAttrVOs; // 产品默认属性
                  if (item.pdAttrVOs && item.pdAttrVOs.length) {
                    item.pdAttrVOs.map(attr => {
                      const attrValues = attr;
                      attrValues.attrValList = [];
                      if (attr.attrId === 'PPATT_0000000001') {
                        // 社保缴费方式
                        attrValues.attrValList = ['2'];
                      } else if (attr.attrId === 'PPATT_0000000002') {
                        // 社保缴费险种
                        attrValues.attrValList = ['3', '4', '5', '6', '7'];
                      } else if (attr.attrId === 'PPATT_0000000003') {
                        // 公积金缴费方式
                        attrValues.attrValList = ['2'];
                      }
                      pd.listAttr.push({
                        attrId: attr.attrId, // 属性id
                        attrName: attr.attrName, // 属性名称
                        dictType: attr.dictType, // 属性字典
                        attrValList:
                          (attr.attrValList &&
                            attr.attrValList.length &&
                            attr.attrValList.join(',')) ||
                          '', // 属性值
                      });
                    });
                  }
                }
              });
            });
          }
        });
        yield put({
          type: 'updateModelData',
          payload: {
            productList: response.data,
            packList,
          },
        });
      } else {
        message.warning(`${response.message || '获取产品属性信息：服务端错误！'}`);
      }
      return response;
    },
    // 获取地区产品价格
    *fetchAreaPrice(
      {
        payload: { areaId, matchList, packIndex, priceId },
      },
      { call, select, put }
    ) {
      const response = yield call(getAreaPrice, { areaId, matchList });
      const packList = yield select(state => state.quosetprice.packList);
      if (response.success) {
        if (response.data && response.data.length) {
          if (
            packList[packIndex] &&
            packList[packIndex].priceList &&
            packList[packIndex].priceList.length
          ) {
            const suggPrice = response.data.reduce(
              (total, currentValue) => total + currentValue.suggPrice || 0,
              0
            );
            if (priceId) {
              packList[packIndex].priceList.forEach((item, index, arr) => {
                const temp = arr;
                if (priceId && priceId === item.id) {
                  temp[index].suggPrice = suggPrice;
                }
              });
            } else {
              packList[packIndex].priceList.forEach((item, index, arr) => {
                const temp = arr;
                temp[index].suggPrice = suggPrice;
              });
            }
          }
        } else {
          message.warning('该地区未配置产品建议售价！');
        }
        yield put({
          type: 'updateModelData',
          payload: {
            packList,
          },
        });
      } else {
        message.warning(`${response.message || '获取执行地产品价格信息：服务端错误！'}`);
      }
    },
    // 提交数据
    submit:[
      function* (_, { call, put, select }) {
      const {
        preQuoInfo: { suppId, custId, custContId, serType, quoName, taxFlag, taxRatio, quoType },
        packList,
      } = yield select(state => state.quosetprice);
      let submitData = {
        suppId,
        custId,
        custContId,
        serType,
        quoName,
        taxFlag,
        taxRatio,
        quoType,
      };
      const submitPackList = JSON.parse(JSON.stringify(packList));
      if (submitPackList.length) {
        submitPackList.map(pack => {
          const temp = pack;
          delete temp.areaPriceId;
          if (pack.listQuoPd && pack.listQuoPd.length) {
            pack.listQuoPd.map(item => {
              const obj = item;
              delete obj.pdAttrVOs;
            });
          }
          if (pack.priceList && pack.priceList.length) {
            pack.priceList.map(item => {
              const tempObj = item;
              tempObj.taxMoney = item.taxMoney || 0;
              // 组装areaId集合
              if(item.areaIdList && item.areaIdList.length) {
                const newarr = item.areaIdList;
                const arr = [];
                newarr.map(items => {
                  arr.push(items.value);
                })
                tempObj.areaId = arr.toString(); // [1,1234] => "1,1234"
              }
              delete tempObj.id;
              delete tempObj.areaIdList;
            });
          }
        });
      }
      submitData = { ...submitData, packList: submitPackList };
      const response = yield call(submit, submitData);
      if (response.success) {
        message.success('新增成功！');
        yield put(
          routerRedux.push({
            pathname: '/salemanage/quotation/finished',
          })
        );
      } else {
        message.warning(`${response.message || '保存失败！'}`);
      }
    },
    { type:'throttle',ms:10000 }
  ]
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
